/*
 * Clase que crea una interfaz grafica para el servidor
 * CLASE SUSTRAIDA DE UNA PAGINA WEB
 */
package servclien;

import javax.swing.*;
import java.awt.*;
import java.awt.event.*;

public final class ServerGUI extends JFrame implements ActionListener, WindowListener {

    private static final long _serialVersionUID = 1L;
    private JButton _stopStart;
    private JTextArea _chat, _event;
    private JTextField _tPortNumber;
    private Server _server;

    /**
     * Constructor, recibe el puerto para ejecutar la conexion
     *
     * @param port Puerto donde se ejecuta la conexion
     */
    ServerGUI(int pPort) {
        super("Chat Server");
        _server = null;
        JPanel north = new JPanel();
        north.add(new JLabel("Port number: "));
        _tPortNumber = new JTextField("  " + pPort);
        north.add(_tPortNumber);
        // to stop or start the server, we start with "Start"
        _stopStart = new JButton("Start");
        _stopStart.addActionListener(this);
        north.add(_stopStart);
        add(north, BorderLayout.NORTH);

        // the event and chat room
        JPanel center = new JPanel(new GridLayout(1, 1));
        _chat = new JTextArea(80, 80);
        _chat.setEditable(false);
        appendRoom("Chat room.\n");
        center.add(new JScrollPane(_chat));
        //event = new JTextArea(80,80);
        //event.setEditable(false);
        //appendEvent("Events log.\n");
        //center.add(new JScrollPane(event));	
        add(center);

        // need to be informed when the user click the close button on the frame
        addWindowListener(this);
        setSize(350, 200);
        setVisible(true);
    }

    /**
     * Concatena el mensaje a las dos areas de texto de la GUI
     *
     * @param pStr Texto a concatenar
     */
    void appendRoom(String pStr) {
        _chat.append(pStr);
        _chat.setCaretPosition(_chat.getText().length() - 1);
    }

    void appendEvent(String pStr) {
        _event.append(pStr);
        _event.setCaretPosition(_chat.getText().length() - 1);
    }

    /**
     * Click a empezar o detener.
     *
     * @param pE Evento
     */
    @Override
    public void actionPerformed(ActionEvent pE) {
        if (_server != null) {
            _server.stop();
            _server = null;
            _tPortNumber.setEditable(true);
            _stopStart.setText("Start");
            return;
        }

        int port;
        try {
            port = Integer.parseInt(_tPortNumber.getText().trim());
        } catch (Exception pEr) {
            appendEvent("Invalid port number");
            return;
        }
        _server = new Server(port, this);
        new ServerRunning().start();
        _stopStart.setText("Stop");
        _tPortNumber.setEditable(false);
    }

    public static void main(String[] pArg) {
        new ServerGUI(1500);
    }

    /**
     * Evento que se ejecuta al cerrar la ventana.
     *
     * @param pE Evento de ventana
     */
    @Override
    public void windowClosing(WindowEvent pE) {
        if (_server != null) {
            try {
                _server.stop();
            } catch (Exception eClose) {
            }
            _server = null;
        }
        dispose();
        System.exit(0);
    }

    @Override
    public void windowClosed(WindowEvent e) {
    }

    @Override
    public void windowOpened(WindowEvent e) {
    }

    @Override
    public void windowIconified(WindowEvent e) {
    }

    @Override
    public void windowDeiconified(WindowEvent e) {
    }

    @Override
    public void windowActivated(WindowEvent e) {
    }

    @Override
    public void windowDeactivated(WindowEvent e) {
    }

    /*
     * Clase interna del hilo que ejecuta el servidor
     */
    class ServerRunning extends Thread {

        @Override
        public void run() {
            _server.start();
            _stopStart.setText("Start");
            _tPortNumber.setEditable(true);
            appendEvent("Server crashed\n");
            _server = null;
        }
    }
}
